package com.example.loggingservice.listener;

import com.example.loggingservice.entity.OperationLog;
import com.example.loggingservice.service.LoggingService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RequiredArgsConstructor
public class LogMessageListener {
    private final LoggingService loggingService;

    @RabbitListener(queues = "user.logs")
    public void handleLogMessage(Map<String, Object> message) {
        try {
            OperationLog log = new OperationLog();
            if (message.get("userId") != null) {
                log.setUserId(Long.valueOf(message.get("userId").toString()));
            }
            if (message.get("action") != null) {
                log.setAction(message.get("action").toString());
            }
            if (message.get("details") != null) {
                log.setDetail(message.get("details").toString());
            }
            if (message.get("ip") != null) {
                log.setIp(message.get("ip").toString());
            }

            loggingService.saveLog(log);
        } catch (Exception e) {
            // 记录错误日志
            System.err.println("Error processing log message: " + e.getMessage());
            throw e; // 重新抛出异常以触发重试机制
        }
    }
}